package com.bigbirdmen.cloud.websocket.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: bzq
 * @Date: 2022/3/2 10:18
 * @Description:
 */
@Component
@ServerEndpoint(value = "/connectWebSocket/{userId}")
//ws://127.0.0.1:9696/connectWebSocket/1
public class WebSocketHandle {

	/**
	 * 在线人数
	 */
	public static int onlineNumber = 0;
	/**
	 * 以用户的姓名为key，WebSocket为对象保存起来
	 * String : key  : 姓名
	 * WebSocket : value : socket 对象
	 */
	private static Map<String, WebSocketHandle> clients = new ConcurrentHashMap<String, WebSocketHandle>();

	/**
	 * 日志
	 */
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 会话
	 */
	private Session session;

	/**
	 * 用户名称
	 */
	private String userId;

	/**
	 * 获取当前websocket 链接人数
	 *
	 * @return int
	 */
	public static synchronized int getOnlineCount() {
		return onlineNumber;
	}

	/**
	 * 建立连接
	 *
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("userId") String userId, Session session) {
		onlineNumber++;
		logger.info("现在来连接的客户id：" + session.getId() + "用户名：" + userId);

		//TODO Service

	}

	@OnError
	public void onError(Session session, Throwable error) {
		logger.info("服务端发生了错误" + error.getMessage());
		//error.printStackTrace();
	}

	/**
	 * 连接关闭
	 */
	@OnClose
	public void onClose() {
		onlineNumber--;
		// TODO service
		logger.info("有连接关闭！ 当前在线人数" + clients.size());
	}

	/**
	 * 收到客户端的消息
	 *
	 * @param message 消息
	 * @param session 会话
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		logger.info("来自客户端消息：" + message + "客户端的id是：" + session.getId());
		// TODO service
	}

	public void sendMessageTo(String message, String touserId) throws IOException {
		for (WebSocketHandle item : clients.values()) {

			System.out.println("在线人员名单  ：" + item.userId.toString());
			if (item.userId.equals(touserId)) {
				item.session.getAsyncRemote().sendText(message);

				break;
			}
		}
	}

	public void sendMessageAll(String message, String fromuserId) throws IOException {
		//遍历一下 给所有的用户推送信息
		for (WebSocketHandle item : clients.values()) {
			//这个是非阻塞的
			item.session.getAsyncRemote().sendText(message);
			//这个是阻塞的
			//item.session.getBasicRemote().sendText(message);
		}
	}

}